package org.uim.cricket.analyzer.parsers.partnerships.impl;

import org.uim.cricket.analyzer.parsers.partnerships.FallOfWicketParsable;
import org.uim.cricket.entities.Player;
import org.uim.cricket.entities.partnerships.FallOfWicket;

public class DefaultFallOfWicketParser implements FallOfWicketParsable {

	@Override
	public FallOfWicket parseFallOfWicket(String source) {
		FallOfWicket fow = new FallOfWicket();
		
		int parapos = source.indexOf('(');
		if (parapos < 0) return null;
		
		String wktAndRuns = source.substring(0, parapos).trim();
		int pos = wktAndRuns.indexOf('-');
		boolean retired = false;
		
		if (wktAndRuns.indexOf('*') >= 0) {
		    retired = true;
		    wktAndRuns = wktAndRuns.replace("*", "");
		}
		
		fow.setWicket(Integer.parseInt(wktAndRuns.substring(0, pos)));
		fow.setFallOfRuns(Integer.parseInt(wktAndRuns.substring(pos+1)));
		fow.setRetiredHurt(retired);
		
		source = source.substring(parapos + 1);
		if (source.endsWith(")")) source = source.substring(0, source.length() - 1);
		String[] playerAndOver = source.split("[,]+");
		
		if (playerAndOver.length >= 1) {
            fow.setOutPlayer(new Player(playerAndOver[0]));
        }
		
		if (retired) {
		    if (playerAndOver.length >= 3) {
		        String ovs = playerAndOver[2];
		        if (ovs.endsWith(" ov")) {
		            ovs = ovs.substring(0, ovs.length() - 3);
		        }
		        fow.setFallOfOver(ovs);
		    }
		} else {
		    if (playerAndOver.length >= 2) {
		        String ovs = playerAndOver[1].trim();
                if (ovs.endsWith(" ov")) {
                    ovs = ovs.substring(0, ovs.length() - 3);
                }
		        fow.setFallOfOver(ovs);
		    }
		}
		
		return fow;
	}

}
